<?php
header("Content-Type: text/plain;charset=utf-8");
$hook = new WebHook();
$hook->start();

class WebHook
{
    private $file = '';
    private $token = '';
    private $timestrap = '';
    private $logFile = '/data/wwwroot/api.huishenche.com/runtime/gitee.log';
    private $secret = 'Theone123456789';
    private $localDir = '/data/wwwroot/';
    private $host = 'api.huishenche.com';
    private $isLog = true;

    public function __construct()
    {
        try {
            $this->file = fopen($this->logFile, "a");
        } catch (Exception $e) {
            $this->log($e->getMessage());
        }

    }

    public function start()
    {
        if (!function_exists('exec')) {
            $this->log('exec被禁用');
            die;
        }

        switch ($_GET['project']) {
            case 'huishenche':
            default:
                $project = 'api.huishenche.com';
                break;
        }

        $project = $this->localDir . $project;
        if (file_exists($project . "/.git")) {
            exec("cd " . $project . " && git stash && git pull" . " 2>&1", $output, $exit);
            $this->log($output);
        }

    }

    /**
     * 记录日志
     */
    public function log($txt)
    {
        if ($this->isLog) {
            fputs($this->file, date("Y-m-d H:i:s") . " [{$_GET['project']}] " . print_r($txt, true) . "\n");
        }
        var_dump($txt);
    }

    /**
     * 验证签名
     */
    public function verify()
    {
        $signStr = $this->timestrap . "\n" . $this->secret;
        $hash = base64_encode(hash_hmac('sha256', $signStr, $this->secret, true));
        if (!hash_equals($this->token, $hash)) {
            $this->log('签名验证失败，gitee签名：' . $this->token . '\n' . '本地签名：' . $hash . '\n' . '签名串：' . $signStr);
            die;
        }
    }

    public function __destruct()
    {
        fclose($this->file);
    }
}
